#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define MAXMEM 144
#define SHMKEY 0x0000ABCD
#define ACCESS 0666

// 12 bytes node_entry
typedef struct node_entry 
{
        int     shid;
        key_t   key;
        void*   pointer;
} node_entry_t;

// 72 bytes
typedef struct node
{
        node_entry_t    name;
        node_entry_t    type;
        node_entry_t    value;
        node_entry_t    empty1;
        node_entry_t    empty2;
        node_entry_t    empty3;
} node_t;

int shid;
node_t* sh_ptr;

void create_start_shm()
{
        
        shid = shmget(SHMKEY, MAXMEM, IPC_CREAT | ACCESS);

        if (shid > 0) 
        {
                sh_ptr = shmat(shid, 0, 0);
                
        } else {
                perror("shmget");
                exit(1);
        }       
}

void connect_shm() 
{
        shid = shmget(SHMKEY, MAXMEM, ACCESS);

        if (shid > 0) 
        {
                sh_ptr = shmat(shid, 0, 0);
        } else {
                perror("shmget");
                exit(1);
        }       
}       

int exits_shm(key_t key) 
{
        int shid2;
        char* sh_ptr2;  

        shid2 = shmget(key, 0, ACCESS);
        if (shid > 0) 
        {
                sh_ptr2 = shmat(shid2, 0, 0);
                return 1;
        } else {
                return 0;
        }       
}

void erase_shm() 
{
        int i;

        for (i=0; i<MAXMEM/sizeof(node_t); i++) {
                ((sh_ptr+i)->name).shid = 0;
                ((sh_ptr+i)->name).key = 0;     
                ((sh_ptr+i)->name).pointer = 0;
                ((sh_ptr+i)->type).shid = 0;
                ((sh_ptr+i)->type).key = 0;     
                ((sh_ptr+i)->type).pointer = 0;
                ((sh_ptr+i)->value).shid = 0;
                ((sh_ptr+i)->value).key = 0;    
                ((sh_ptr+i)->value).pointer = 0;
                ((sh_ptr+i)->empty1).shid = 0;
                ((sh_ptr+i)->empty1).key = 0;   
                ((sh_ptr+i)->empty1).pointer = 0;
                ((sh_ptr+i)->empty2).shid = 0;
                ((sh_ptr+i)->empty2).key = 0;   
                ((sh_ptr+i)->empty2).pointer = 0;
                ((sh_ptr+i)->empty3).shid = 0;
                ((sh_ptr+i)->empty3).key = 0;   
                ((sh_ptr+i)->empty3).pointer = 0;
        }


}

void print_shm() 
{
        int i,j;
        char* ptr;

        ptr = (char*)sh_ptr;

        for (i=0;i<MAXMEM;i+=12) {
                for (j=0;j<12;j++) {
                        printf("0x%02x ", *(ptr));
                        ptr++;                  
                }
                printf("\n");
        }
}


int main(int argc, char** argv)
{
        create_start_shm();
        erase_shm();
        connect_shm();
        print_shm();    
        

}

